package com.tjec.project.businessStandardLibrary.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.tjec.common.constant.AttachmentConstants;
import com.tjec.common.enums.CodeNum;
import com.tjec.common.enums.NumCode;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.ServletUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.framework.security.service.TokenService;
import com.tjec.project.system.domain.BmsAttachment;
import com.tjec.project.system.domain.BmsCategoryAssociated;
import com.tjec.project.system.domain.BmsMdArea;
import com.tjec.project.system.domain.BmsMdBusinessCategory;
import com.tjec.project.system.mapper.BmsAttachmentMapper;
import com.tjec.project.system.mapper.BmsCategoryAssociatedMapper;
import com.tjec.project.system.mapper.BmsMdAreaMapper;
import com.tjec.project.system.mapper.BmsMdBusinessCategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tjec.project.businessStandardLibrary.mapper.BmsKnowledgeCaseMapper;
import com.tjec.project.businessStandardLibrary.domain.BmsKnowledgeCase;
import com.tjec.project.businessStandardLibrary.service.IBmsKnowledgeCaseService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 典型案例Service业务层处理
 * 
 * @author pangyognfeng
 * @date 2020-04-21
 */
@Service
public class BmsKnowledgeCaseServiceImpl implements IBmsKnowledgeCaseService 
{
    @Autowired
    private BmsKnowledgeCaseMapper bmsKnowledgeCaseMapper;
    @Autowired
    private BmsMdBusinessCategoryMapper bmsMdBusinessCategoryMapper;
    @Autowired
    private BmsAttachmentMapper bmsAttachmentMapper;
    @Autowired
    private BmsCategoryAssociatedMapper bmsCategoryAssociatedMapper;
    @Autowired
    private BmsMdAreaMapper bmsMdAreaMapper;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询典型案例
     * 
     * @param guid 典型案例ID
     * @return 典型案例
     */
    @Override
    public BmsKnowledgeCase selectBmsKnowledgeCaseByGuid(String guid)
    {
        return bmsKnowledgeCaseMapper.selectBmsKnowledgeCaseByGuid(guid);
    }
    /**
     * 查询典型案例
     *
     * @param guid 典型案例ID
     * @return 典型案例
     */
    @Override
    public BmsKnowledgeCase selectBmsKnowledgeCaseByGuiddetails(String guid)
    {
        BmsKnowledgeCase blc =bmsKnowledgeCaseMapper.selectBmsKnowledgeCaseByGuiddetails(guid);
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            Date date = null;
            if(blc.getYear()!=null) {
                // 注意格式需要与上面一致，不然会出现异常
                date = sdf.parse(String.valueOf(blc.getYear()));
            }
            
            blc.setDate(date);
            String proviceName=blc.getProvince()==null?"":blc.getProvince();
            String cityName=blc.getCity()==null?"":blc.getCity();
            ArrayList<String> cityIds= new ArrayList<String>();
            if(proviceName!=null && proviceName!="") {
            	BmsMdArea pro = bmsMdAreaMapper.selectBmsMdAreaByName(proviceName,1);
            	if(pro!=null) {
            		cityIds.add(pro.getGuid());
            	}
            }
            if(cityName!=null && cityName!="" ) {
            	BmsMdArea area = bmsMdAreaMapper.selectBmsMdAreaByName(cityName,2);
            	if(area!=null) {
            		cityIds.add(area.getGuid());
            	}
            }
            
            
            blc.setCitys(cityIds);
            blc.setCity(proviceName+cityName);
            List<BmsMdBusinessCategory> bms = blc.getBusinessCategorys();
            List<String> lists= new ArrayList<String>();
            for (BmsMdBusinessCategory bmsMdBusinessCategory:bms) {
                lists.add(bmsMdBusinessCategory.getGuid()) ;
            }
            blc.setBusinessCategoryGuids(lists);
            ArrayList<String> atmlists= new ArrayList<String>();
            List<BmsAttachment> bmsAtms = blc.getAttachments();
            for (BmsAttachment bmsAttachment:bmsAtms) {
                atmlists.add(bmsAttachment.getGuid()) ;
            }
            blc.setAttachmentIds(atmlists);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        blc.setAttachments(bmsAttachmentMapper.queryAttachmentByBizId(blc.getGuid()));
        blc.setBusinessCategorys(bmsMdBusinessCategoryMapper.selectBusinessCategoryByCategoryAssociatedId(blc.getGuid()));
        return blc;
    }
    /**
     * 查询典型案例列表
     * 
     * @param bmsKnowledgeCase 典型案例
     * @return 典型案例
     */
    @Override
    public List<BmsKnowledgeCase> selectBmsKnowledgeCaseList(BmsKnowledgeCase bmsKnowledgeCase)
    {

        return bmsKnowledgeCaseMapper.selectBmsKnowledgeCaseList(bmsKnowledgeCase);
    }

    /**
     * 新增典型案例
     * 
     * @param bmsKnowledgeCase 典型案例
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertBmsKnowledgeCase(BmsKnowledgeCase bmsKnowledgeCase)
    { bmsKnowledgeCase.setCreateTime(DateUtils.getNowDate());
        String guid = UUID.randomUUID().toString();
        bmsKnowledgeCase.setGuid(guid);
        List<String> lists= bmsKnowledgeCase.getCitys();
        if(lists==null||lists.equals("")||lists.isEmpty()){

        }else {
            bmsKnowledgeCase.setProvince(bmsMdAreaMapper.selectBmsMdAreaByGuid(lists.get(0)).getCname());
            if(lists.size()>1) {
            	 bmsKnowledgeCase.setCity(bmsMdAreaMapper.selectBmsMdAreaByGuid(lists.get(1)).getCname());
            }
           
        }
        int res=bmsKnowledgeCaseMapper.insertBmsKnowledgeCase(bmsKnowledgeCase);
        //典型案例guid
        ArrayList<String> attachments = bmsKnowledgeCase.getAttachmentIds();

        if(attachments==null||attachments.equals("")||attachments.isEmpty()){

        }else {
            //更新附件biz_id
            bmsAttachmentMapper.updateBmsAttachmentByGuidsUpdateBiz(attachments, guid, AttachmentConstants.KNOWLEDGE_CASE, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
        }
        List<String> categorys = bmsKnowledgeCase.getBusinessCategoryGuids();
        if(categorys!=null && categorys.size()>0) {
        	 //添加关联库的数据  业务类别的关联
            for (String bms:categorys) {
                BmsCategoryAssociated associated = new BmsCategoryAssociated();
                associated.setCategoryGuid(bms);
                associated.setParentGuid(guid);
                associated.setGuid(UUID.randomUUID().toString());
                associated.setFlag(CodeNum.ONE.getCode());
                bmsCategoryAssociatedMapper.insertBmsCategoryAssociated(associated);
            }
        }
       
        return res;
    }

    /**
     * 修改典型案例
     * 
     * @param bmsKnowledgeCase 典型案例
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBmsKnowledgeCase(BmsKnowledgeCase bmsKnowledgeCase)
    {
        bmsKnowledgeCase.setUpdateTime(DateUtils.getNowDate());
        List<String> lists= bmsKnowledgeCase.getCitys();
        if(lists==null||lists.equals("")||lists.isEmpty()){

        }else {
            bmsKnowledgeCase.setProvince(bmsMdAreaMapper.selectBmsMdAreaByGuid(lists.get(0)).getCname());
            if(lists.size()>1) {
            	bmsKnowledgeCase.setCity(bmsMdAreaMapper.selectBmsMdAreaByGuid(lists.get(1)).getCname());
            }else {
            	bmsKnowledgeCase.setCity(null);
            }
        }
         int res= bmsKnowledgeCaseMapper.updateBmsKnowledgeCase(bmsKnowledgeCase);
        //先把上一次的附件去掉
        String guid=bmsKnowledgeCase.getGuid();
        bmsAttachmentMapper.updateBmsAttachmentByGuid(guid, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
        //对新的附件需要修改附件表的biz_id
        ArrayList<String> attachments = bmsKnowledgeCase.getAttachmentIds();
        if(attachments==null||attachments.equals("")||attachments.isEmpty()){}else {

            bmsAttachmentMapper.updateBmsAttachmentByGuidsUpdateBiz(attachments, guid, AttachmentConstants.KNOWLEDGE_CASE, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
        }
        //对业务类别进行修改先删除在重现添加
        bmsCategoryAssociatedMapper.deleteBmsCategoryAssociatedByParentId(guid);
        //添加
        List<String> categorys = bmsKnowledgeCase.getBusinessCategoryGuids();
        //添加关联库的数据  业务类别的关联
        for (String bms:categorys) {
            BmsCategoryAssociated associated = new BmsCategoryAssociated();
            associated.setCategoryGuid(bms);
            associated.setParentGuid(guid);
            associated.setGuid(UUID.randomUUID().toString());
            associated.setFlag(CodeNum.ONE.getCode());
            bmsCategoryAssociatedMapper.insertBmsCategoryAssociated(associated);
        }
        return res;
    }

    /**
     * 批量删除典型案例
     * 
     * @param guids 需要删除的典型案例ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBmsKnowledgeCaseByGuids(String[] guids)
    {
        int res=bmsKnowledgeCaseMapper.deleteBmsKnowledgeCaseByGuids(guids);
        //删除所有的业务类别关联表数据
        bmsCategoryAssociatedMapper.deleteBmsCategoryAssociatedByParentIds(guids);
        //删除所有的附件数据。逻辑删除
        bmsAttachmentMapper.updateBmsAttachmentByBizId(guids, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
        return res;
    }

    /**
     * 删除典型案例信息
     * 
     * @param guid 典型案例ID
     * @return 结果
     */
    @Override
    public int deleteBmsKnowledgeCaseByGuid(String guid)
    {
        return bmsKnowledgeCaseMapper.deleteBmsKnowledgeCaseByGuid(guid);
    }

    /**
     *
     *@describe 典型案例查询页面
     *@params [bmsKnowledgeCase]
     *@return java.util.List<com.tjec.project.businessStandardLibrary.domain.BmsKnowledgeCase>
     *@author VillWang
     *@date 2020/4/28
     *@other
     *
     */

    @Override
    public List<BmsKnowledgeCase> selectBmsKnowledgeCaseTreeList(BmsKnowledgeCase bmsKnowledgeCase) {


        String businessCategoryId=bmsKnowledgeCase.getBusinessCategoryId();
        List<String> lists = bmsKnowledgeCase.getCitys();
        if(lists==null||lists.equals("")||lists.isEmpty()){

        }else {
            bmsKnowledgeCase.setProvince(bmsMdAreaMapper.selectBmsMdAreaByGuid(lists.get(0)).getCname());
            if(lists.size()>1) {
            	bmsKnowledgeCase.setCity(bmsMdAreaMapper.selectBmsMdAreaByGuid(lists.get(1)).getCname());
            }
        }
        List<String> ids=new ArrayList<>();;
        List<BmsKnowledgeCase> bms=new ArrayList<>();
        int level = 0;
        //业务树查询
        if(StringUtils.isNotBlank(businessCategoryId)){
            level = businessLevel(businessCategoryId);

            if(level==CodeNum.ONE.getCode()){
                ids= bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryChildIdsOne(businessCategoryId);
            }else if(level==CodeNum.TWO.getCode()){
               //对于只有两级的问题
                ids= bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryChildIdsTwo(businessCategoryId);
            }else {
                ids.add(businessCategoryId);
            }
            //没有第三层的问题
            if(ids.isEmpty()){
                ids.add(businessCategoryId);
            }
            bmsKnowledgeCase.setGuids(ids);
            bms=bmsKnowledgeCaseMapper.selectBmsKnowledgeCaseListByGuIds(bmsKnowledgeCase);
        }else {
            //不点业务树查询
           // bms=bmsKnowledgeCaseMapper.selectBmsKnowledgeCaseListNoTree(bmsKnowledgeCase);
            bms=bmsKnowledgeCaseMapper.selectBmsKnowledgeCaseListByGuIds(bmsKnowledgeCase);
        }
        if(ids.size()==1) {
        	 bms = bmsKnowledgeCaseList(bms,businessCategoryId);
        }else {
        	 bms = bmsKnowledgeCaseList(bms);
        }
       
        return bms;
    }
    /**
     *
     *@describe 组装数据
     *@params [bms]
     *@return java.util.List<com.tjec.project.businessStandardLibrary.domain.BmsKnowledgeCase>
     *@author VillWang
     *@date 2020/6/16
     *@other
     *
     */
    @Override
    public List<BmsKnowledgeCase> bmsKnowledgeCaseList(List<BmsKnowledgeCase> bms) {
        for (BmsKnowledgeCase bkc:bms) {
             String guid= bkc.getGuid();
            List<BmsAttachment> bmsAttachments = bmsAttachmentMapper.queryAttachmentByBizId(guid);
            List<BmsMdBusinessCategory> bmsMdBusinessCategories = bmsMdBusinessCategoryMapper.selectBusinessCategoryByCategoryAssociatedId(guid);
            bkc.setAttachments(bmsAttachments);
            bkc.setBusinessCategorys(bmsMdBusinessCategories);
        }

        return bms;

    }
    
    /**
    *
    *@describe 组装数据
    *@params [bms]
    *@return java.util.List<com.tjec.project.businessStandardLibrary.domain.BmsKnowledgeCase>
    *@author VillWang
    *@date 2020/6/16
    *@other
    *
    */
   @Override
   public List<BmsKnowledgeCase> bmsKnowledgeCaseList(List<BmsKnowledgeCase> bms, String businessCategoryId) {
		for (BmsKnowledgeCase bkc:bms) {
            String guid= bkc.getGuid();
           List<BmsAttachment> bmsAttachments = bmsAttachmentMapper.queryAttachmentByBizId(guid);
           BmsMdBusinessCategory bmsMdBusinessCategory = bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryByGuId(businessCategoryId);
           List<BmsMdBusinessCategory> bmsMdBusinessCategories = new ArrayList<BmsMdBusinessCategory>();
           bmsMdBusinessCategories.add(bmsMdBusinessCategory);
           bkc.setAttachments(bmsAttachments);
           bkc.setBusinessCategorys(bmsMdBusinessCategories);
       }

       return bms;

   }
    /**
     *
     *@describe   获取业务类别的层级
     *@params [businessCategoryId]
     *@return java.lang.String
     *@author VillWang
     *@date 2020/4/27
     *@other
     *
     */
    public int businessLevel(String businessCategoryId) {

        BmsMdBusinessCategory bms=  bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryByGuId(businessCategoryId);
        String parentId= bms.getParentId();
        //获取下级定位是否只有2层的问题
        BmsMdBusinessCategory bmsMdBusinessCategorynew = new BmsMdBusinessCategory();
        bmsMdBusinessCategorynew.setParentId(businessCategoryId);
        List<BmsMdBusinessCategory> bmsCategory= bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryList(bmsMdBusinessCategorynew);
        int flag=0;
        if(bmsCategory==null||bmsCategory.isEmpty()||bmsCategory.equals("")){
            //处理没有二级  和三级的  一级菜单
           return CodeNum.THREE.getCode();
        }else {
            for (BmsMdBusinessCategory bms2 : bmsCategory) {

                bmsMdBusinessCategorynew.setParentId(bms2.getGuid());
                List<BmsMdBusinessCategory> bmsCategory3= bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryList(bmsMdBusinessCategorynew);
                for (BmsMdBusinessCategory bms3:bmsCategory3) {
                    if(bms3==null||bms3.equals("")){
                    }else {
                        //标记是否有第三级
                        flag=1;
                    }
                }

            }
        }
        if(flag==0){
            //标记是否有第三级
            return CodeNum.TWO.getCode();
        }
        //第一层
        if(parentId.equals(NumCode.ZERO.getCode())){
            return CodeNum.ONE.getCode();
        }else {
            //第二层
            BmsMdBusinessCategory bms2=  bmsMdBusinessCategoryMapper.selectBmsMdBusinessCategoryByGuId(bms.getParentId());
            String parentId2= bms2.getParentId();
            if(parentId2.equals(NumCode.ZERO.getCode())){
                return CodeNum.TWO.getCode();
            }else {
                //第三层
                return CodeNum.THREE.getCode();
            }
        }

    }
}
